from typing import Union
from PIL import Image
from io import BytesIO

from Server import var


def thresholdMinAndMax(src, minV, maxV):
    """
    阈值限定，当输入值超出边界值时返回边界值

    :param src: 输入值
    :param minV: 最小值限定
    :param maxV: 最大值限定
    :return:
    """
    if src < minV:
        return minV
    if src > maxV:
        return maxV
    return src


def read404image() -> bytes:
    """
    读取 404 图片（有时候由于资源丢失可用404图片代替显示）

    :return:
    """
    return readFile(var.DEF_RES + '/icon/404.png')


def readFile(filepath: str, mode='rb', default: Union[bytes, str] = b'') -> Union[bytes, str]:
    """
    快捷读取文件内容

    :param filepath: 文件路径
    :param mode: 读取模式
    :param default: 异常处理值
    :return:
    """
    try:
        with open(filepath, mode) as f:
            return f.read()
    except:
        return default


def imageCompress(imgPath: str, quality=10, scale=1) -> bytes:
    """
    图片压缩

    :param imgPath: 图片路径
    :param quality: 压缩质量，0~99，数字越小越模糊，压缩的越厉害，默认为 10
    :param scale: 缩放比例
    :return:
    """
    quality = thresholdMinAndMax(quality, 0, 99)
    scale = thresholdMinAndMax(scale, 0.1, 1)
    try:
        img = Image.open(imgPath)
        w, h = img.size
        sw, sh = int(w * scale), int(h * scale)
        scaleImg = img.resize((sw, sh))
        imgBytesIO = BytesIO()
        scaleImg.save(imgBytesIO, 'JPEG', quality=quality)
        return imgBytesIO.getvalue()
    except:  # 压缩失败就返回原图
        return readFile(imgPath)
